package com.hjrpc.babyyamall.authserver.service;

import com.hjrpc.babyyamall.authserver.feign.SmsFeignService;
import com.hjrpc.babyyamall.authserver.util.NumberRandomUtil;
import com.hjrpc.common.constant.AuthServerConstant;
import com.hjrpc.common.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    SmsFeignService smsFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    // 最小间隔时间 单位：s
    public static final int MIN_INTERVAL_TIME = 60;

    @Override
    public R sendCode(String phone) {
        String value = stringRedisTemplate.opsForValue().get(AuthServerConstant.AUTH_REDIS_PREFIX + phone);

        // 判断redis中已经存在且没有超过 60 s
        if (StringUtils.isNotBlank(value) &&
                (System.currentTimeMillis() - Long.valueOf(value.split("_")[1])) <= MIN_INTERVAL_TIME * 1000) {
            return R.error("在" + MIN_INTERVAL_TIME + "秒内无法再次发送短信");
        }

        // 生成随机的数字验证码
        String code = NumberRandomUtil.getString(6);

        // 发送验证码
        R r = smsFeignService.sendSmsCode(phone, code);

        // 将验证码存储到redis中缓存起来
        if (r.isSuccess()) {
            stringRedisTemplate.opsForValue().set(AuthServerConstant.AUTH_REDIS_PREFIX + phone,
                    code + "_" + System.currentTimeMillis(), 10, TimeUnit.MINUTES);
        }
        return r;
    }
}
